package com.crt.uav.aspect;

import java.util.Arrays;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.crt.uav.common.utils.JSON;
import com.crt.uav.persistence.entity.UavApiLog;
import com.crt.uav.persistence.service.UavApiLogService;

@Aspect
@Component
public class ApiLoggerAspect {

    private static final Logger logger = LoggerFactory.getLogger(ApiLoggerAspect.class);

    @Autowired(required = false)
    @Qualifier("uavApiLogService")
    private UavApiLogService uavApiLogService;

    // 定义切点，拦截所有 com.crt 包及其子包中的方法
    @Pointcut("execution(* com.crt.uav.api..*(..))")
    public void apiPointcut() {
        // 切点方法，无需实现
    }


    // 方法执行前打印日志
    @Around("apiPointcut()")
    public Object logApiInf(ProceedingJoinPoint joinPoint) throws Throwable {

        // 获取方法名称和参数
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getSignature().getDeclaringTypeName();
        Object[] args = joinPoint.getArgs();
        logger.info("方法调用开始: {}.{}()，参数: {}", className, methodName, Arrays.toString(args));

        long startTime = System.currentTimeMillis(); // 方法开始时间
        Object result = null; // 方法返回结果
        try {
            result = joinPoint.proceed(); // 执行目标方法
        } catch (Exception e) {
            logger.error("方法调用异常: {}.{}()，异常信息: {}", className, methodName, e.getMessage(), e);
            throw e; // 将异常抛出，交由全局异常处理器处理
        }finally {
            long endTime = System.currentTimeMillis(); // 方法结束时间
            long executionTime = endTime - startTime;
            // 打印返回结果和执行时间
            logger.info("方法调用结束: {}.{}()，返回结果: {}，执行耗时: {} ms", className, methodName, result, executionTime);
            try {
                UavApiLog uavApiLog = new UavApiLog();
                uavApiLog.setMethod(methodName);
                
                uavApiLog.setReqParam(JSON.stringify(args));
                uavApiLog.setRespBody(JSON.stringify(result));
                uavApiLog.setApiTime((int) executionTime);
                uavApiLog.setProtocol("HTTP");
                uavApiLogService.saveApiInfo(uavApiLog);
            } catch (Exception e) {
                logger.error("保存API日志失败: {}.{}()，异常信息: {}", className, methodName, e.getMessage(), e);
            }

        }

        return result; // 返回目标方法的执行结果
    }
}
